<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace app\shop\api;

use app\common\api\BaseApi;
use app\shop\model\ScoreGoods;

use Admin\Api\MemberApi;
use Common\Api\ExchangeLogApi;
use Shop\Api\RedEnvelopeApi;
use Admin\Api\AddressApi;
use Tool\Api\AreaApi;
use Tool\Api\CityApi;
use Tool\Api\ProvinceApi;

class ScoreGoodsApi extends BaseApi{
  //积分商品类型 优惠券数额写在前面+>intval
  public static $types = [
    '0'    =>'未知',
    '1'    =>'商品',
    '6083' =>'10元优惠券',
    '6084' =>'20元优惠券',
    '6085' =>'50元优惠券',
  ];
  const QUERY    = "common/ScoreGoodsApi/myFind";
  const PAGE     = "common/ScoreGoodsApi/page";
  const ORPAGE   = "common/ScoreGoodsApi/query";
  const DELETE   = "common/ScoreGoodsApi/delete";
  const ADD      = "common/ScoreGoodsApi/add";
  const SAVE     = "common/ScoreGoodsApi/save";
  const DETAIL   = "common/ScoreGoodsApi/detail";
  const GET_INFO = "common/ScoreGoodsApi/getInfo";
  const CHANGE   = "common/ScoreGoodsApi/shelf";
  const GETPAYURL= "common/ScoreGoodsApi/getPayUrl";
  const EXCHANGE = "common/ScoreGoodsApi/exchange";

  public function myFind($start,$length,$order="create_time desc"){
    // $order = '';
    // return $this -> apiReturnSuc($order);
    $where = array('onshelf'=>1);//,'status'=>1
    $r     = $this-> model //->cache(true)
            // ->alias('g')
            // ->relation(true)
            // ->join(C('DB_PREFIX').'user_picture p ON g.main_img = p.id')
            // ->field('g.*,p.path')
            ->where($where)->limit($start,$length)->order($order)->select();
    // dump($r);
    // dump($this->getLastSql());exit;
    return $this -> apiReturnSuc($r);
  }

  public function shelf($gid,$onshelf){
    if($r = $this->model->where(array('id'=>$gid))->setField('onshelf',$onshelf))
      return $this->apiReturnSuc($r);//->cache(true)
    else
      return $this->apiReturnErr($r);
  }

  public function page($where,$page){
    // $where = array('game_id'=>$gid);
    $page = array('curpage'=>$page,'size'=>10);

    $r = $this -> model ->where($where);//->cache(true)

    $list = $r -> page($page['curpage'].','.$page['size']) -> select();
    if ($list === false) {
      $error = $this -> model -> getDbError();
      return $this -> apiReturnErr($error);
    }
    $count = $r -> count();
    $Page = new \Think\Page($count, $page['size']);
    //分页跳转的时候保证查询条件
    if ($params !== false) {
      foreach ($params as $key => $val) {
        $Page -> parameter[$key] = urlencode($val);
      }
    }
      $show = $Page -> show();
      return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
  }
  //积分商品兑换
  public function exchange($uid,$psw,$pid){
    $msg = [];$msg['status'] = true;
    $member = apiCall(MemberApi::GET_INFO,[['uid'=>$uid]]);
    if(!$member['status'])
    {
        $msg['info']   = '非法用户';
        $msg['status'] = false;
        return $msg;
    }
    $sgoods = $this->getInfo(['id'=>$pid]);
    $score  = intval($sgoods['info']['score']);
    $price  = $sgoods['info']['price'];
    if(0==$score){
      $msg['info']   = '积分商品兑换积分不能为0,请联系客服人员修改';
      $msg['status'] = false;
      return $msg;
    }
    $mscore   = intval($member['info']['score']);
    if( $mscore < $score ){
      $msg['info']   = '积分不足';
      $msg['status'] = false;
      return $msg;
    }
    $this->model-> startTrans();
    //减少积分
    $r = apiCall(MemberApi::SET_DEC,array(array('uid'=>$uid),'score',$score));
    if(!$r['status']){
        $msg['info']   = '系统错误： SCORE:DEC:ERROR';
        $msg['status'] = false;
        return $msg;
    }
    $exStatus = ($price == 0)?0:-1;
    // dump($exStatus);exit;
    $member['info']['score'] = $mscore - $score;
    //增加记录
    $map = array(
        'pid'              =>$pid
        ,'uid'             =>$uid
        ,'pname'           =>$sgoods['info']['name']
        ,'exchange_status' =>$exStatus
        ,'score'           =>$score
        ,'price'           =>$price
        // ,'pay_code'        =>$code
    );

    $type = intval($sgoods['info']['dt_goods_type']);
    $real = ($type && 1!==$type)?true:false;
    if($real){
      //发放优惠券
      $sname = $this->types[$type];
      $value = intval($sname);
      $map['pay_code'] = $sname.':'.$value;
      $map['exchange_status'] = 1;
      $id = $this->addExLog($map);
      //add $num red-envelope to user[$uid]
      $e                = array();
      $e['uid']         = $uid;
      $e['get_time']    = NOW_TIME;
      $e['money']       = $value;
      $e['use_status']  = 0;
      $e['tpl_id']      = 12;         //无门槛
      $e['expire_time'] = 86400*365; //365天 //优惠券
      $e['notes']       = '成功兑换'.$sname.',有效期1年';
      $result           = apiCall(RedEnvelopeApi::ADD,array($e));
      // dump($result);exit;
      if(!$result['status']){
          $status = false;
          $this->model->rollback();
          $msg    = '优惠券发放失败';
      }
      $t=1;
    }else{
      $id = $this->addExLog($map);
      //前往 收货地址 + 支付/以后支付
      $t=0;
    }
    $this->model->commit();
    $url = U('ExchangeLog/pay',array('uid'=>$uid,'psw'=>$psw,'id'=>$id,'type'=>$t));
    if($id) $msg['info']   = $url;
    return $msg;
  }
  private function addExLog($map){
    $r = apiCall(ExchangeLogApi::ADD,[$map]);
    // dump($r);exit;
    if(!$r['status'] || !$r['info']){
      $this->model->rollback();
      $this->error('系统错误：用户兑换:记录失败');
    }else{
      return intval($r['info']);
    }
  }
  //初始化
  protected function _init(){
    $this -> model  = new ScoreGoodsModel();
  }

  public function detail($id){
    $entry = $this-> model->find($id);// ->cache(true)
    // dump($entry);exit;
    return $entry;
  }
  public function getPayUrl($uid,$price,$psw){
    $now  = time();
    $code = 'S'.$now.'U'.$uid;
    $name = '订单'.$code;
    $desc = $name;
    //保留2位
    $total_price = round($price,2);
    $info = array(
        'code'=>$code,
        'name'=>$name,
        'desc'=>$desc,
        //@author 老胖子-何必都 <hebiduhebi@126.com>
        //转换成字符串，否则IOS端解析成数字类型时精度会有问题，比如74.10 被解析成74.09999999999999,从而导致APP端验证失败!
        'total_price'=>strval($total_price)
    );

    $encode = urlencode($code.$name.$desc.$total_price);
    $encode = md5(strtolower($encode));

    $info['key'] = pay_encrypt_md5($encode);
    $info['show_url'] = '';//U('Webview/ExchangeLog/payBack',array('uid'=>$uid,'psw'=>$psw));
    return array('url'=>'com.itboye.sunsun-china://?type=SUNSUN_ALIPAY_FOR_SCOREGOODS&code='.$info['code'].'&name='.$info['name'].'&desc='.$info['desc'].'&total_price='.$info['total_price'].'&key='.$info['key'].'&show_url='.$info['show_url'],'code'=>$info['code']);
    // return array('url'=>'com.itboye.sunsunchina://?type=SUNSUN_ALIPAY_FOR_SCOREGOODS&code='.$info['code'].'&name='.$info['name'].'&desc='.$info['desc'].'&total_price='.$info['total_price'].'&key='.$info['key'].'&show_url='.$info['show_url'],'code'=>$info['code']);

    }
}